package fsmi.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import fsmi.daoservice.SimpleDBPool;

public class DBPool implements SimpleDBPool {

	private DataSource ds;
	public static int DEFAULT_CONN_COUNT = 5;
	private static DBPool single = null;
	private List<Connection> connList;

	private DBPool() {
		InitialContext jndiContext = null;
		Properties properties = new Properties();
		properties.put(javax.naming.Context.PROVIDER_URL, "jnp:///");
		properties.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
		try {
			jndiContext = new InitialContext(properties);
			ds = (DataSource) jndiContext.lookup("java:comp/env/jdbc/homeworkCheck");
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		connList = new LinkedList<Connection>();
	}

	public synchronized static DBPool getInstance() {
		// if this class haven't created a instance,init it and return
		if (single == null) {
			single = new DBPool();
			single.createConn(DEFAULT_CONN_COUNT);
			return single;
		} else {
			return single;
		}
	}

	@Override
	public void createConn(int count) {
		// TODO Auto-generated method stub
		Connection conn = null;
		for (int i = 0; i < count; i++) {
			try {
				conn = ds.getConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			connList.add(conn);
		}
	}

	@Override
	public void destroyConn() {
		// TODO Auto-generated method stub
		Iterator<Connection> itor = connList.iterator();
		Connection conn = null;
		while (itor.hasNext()) {
			conn = itor.next();
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		connList = null;
	}

	@Override
	public int getConnCount() {
		// TODO Auto-generated method stub
		int count = connList.size();
		return count;
	}

	@Override
	public Connection getConn() {
		// TODO Auto-generated method stub
		Connection conn = connList.remove(0);
		return conn;
	}

	@Override
	public void returnConn(Connection conn) {
		// TODO Auto-generated method stub
		connList.add(conn);
	}

}
